package com.panopset.io;

import static com.panopset.Util.*;
import static com.panopset.UtilIO.*;

import java.io.File;
import java.io.IOException;
import java.io.StringWriter;

import com.panopset.Strings;

/**
 * Access to a flat jar file.
 *
 * Useful for a set of icons used in a video game sprite, for example.
 *
 * @author Karl Dinwiddie
 *
 */
public class JarResourceCollection {

    /**
     * Extension.
     */
    private String pextension;

    /**
     * Jar file.
     */
    private final File pjarFile;

    /**
     * Jar resources.
     */
    private final JarResources pjarResources;

    /**
     * Use this constructor if you would like a homogeneous set of resources,
     * for example all ".png" images.
     *
     * @param srcPath
     *            Java package path, for example
     *            "/com/panopset/nls/flagicons.jar"
     * @param workPath
     *            The jar must be extracted from the Java class resource to a
     *            work directory.
     * @param extension
     *            ".png" for example
     * @throws IOException
     *             IO Exception.
     */
    public JarResourceCollection(final String srcPath, final String workPath,
            final String extension) throws IOException {
        pextension = extension;
        pjarFile = savePackageResource(srcPath, workPath);
        pjarResources = new JarResources(this.pjarFile);
    }

    /**
     * Use this constructor if you would like access to all objects in the jar.
     *
     * @param srcPath Source path.
     * @param workPath Work path.
     * @throws IOException
     *             IO Exception.
     */
    public JarResourceCollection(final String srcPath, final String workPath)
            throws IOException {
        this(srcPath, workPath, "");
    }

    /**
     * Extract and list resources.
     *
     * @param targetPath
     *            Directory you would like the resources stored.
     * @return String list of resources, with the extension dropped.
     * @throws IOException
     *             IO Exception.
     */
    public final String extractAndListResources(final String targetPath)
            throws IOException {
        StringWriter sw = new StringWriter();
        for (String k : pjarResources.getSizes().keySet()) {
            if (!isPopulated(k) || k.indexOf(pextension) > 0) {
                String name = dropPath(k);
                sw.append(dropExtension(name));
                sw.append(Strings.getEol());
                saveBytesToFile(pjarResources.getResource(k), new File(
                        targetPath + "/" + name));
            }
        }
        return sw.toString();
    }

}
